package com.moon.app;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.NinePatchDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.moon.R;
import com.moon.common.AbstractActivity;
import com.moon.constants.MoonConstants;
import com.moon.model.JsonResult;
import com.moon.utils.HttpClientUtils;
import com.moon.utils.ImageLoadUtils;
import com.moon.utils.JacksonUtils;

/**
 * 广场
 * 
 * @author paul
 * @date 2014年5月11日
 */
public class TopicSendActivity extends AbstractActivity {
    public static final String TAG     = TopicSendActivity.class.getSimpleName();

    EditText                    title;
    EditText                    content;
    ImageView               squareImage1;
    ImageView               squareImage2;
    ImageView               squareImage3;
    int                         selectedImageNum;                                 //本次选择的是哪个图片
    String                      topicId;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.topic_send);

        Intent intent = getIntent();
        topicId = intent.getStringExtra(MoonConstants.TOPIC_CATEGORY_ID);

        title = (EditText) findViewById(R.id.topic_title);
        content = (EditText) findViewById(R.id.topic_content);
        squareImage1 = (ImageView) findViewById(R.id.topic_image_1);
        squareImage1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                ShowPickDialog();
                selectedImageNum = 1;
                //squareImage2.setVisibility(View.VISIBLE);
            }
        });
//        squareImage1.setOnMeasureListener(new OnMeasureListener() {
//            @Override
//            public void onMeasureSize(int width, int height) {
//                mPoint1.set(width, height);
//            }
//        });

        squareImage2 = (ImageView) findViewById(R.id.topic_image_2);
        squareImage2.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                ShowPickDialog();
                selectedImageNum = 2;
                //squareImage3.setVisibility(View.VISIBLE);
            }
        });
//        squareImage2.setOnMeasureListener(new OnMeasureListener() {
//            @Override
//            public void onMeasureSize(int width, int height) {
//                mPoint1.set(width, height);
//            }
//        });

        squareImage3 = (ImageView) findViewById(R.id.topic_image_3);
        squareImage3.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                ShowPickDialog();
                selectedImageNum = 3;

            }
        });
//        squareImage3.setOnMeasureListener(new OnMeasureListener() {
//            @Override
//            public void onMeasureSize(int width, int height) {
//                mPoint1.set(width, height);
//            }
//        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuItem send = menu.add("send");
        send.setIcon(R.drawable.moon_check);
        send.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);//作为按钮显示
        send.setOnMenuItemClickListener(new OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {

                String message = validate();
                if (StringUtils.isNotBlank(message)) {
                    Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
                    return false;
                }

                Bitmap bitmap1 = getBitmap(squareImage1);
                //TODO 这个压缩没意义  后面是先存到手机 再上传
                //bitmap1 = ImageCompressUtils.compressImage(bitmap1,Bitmap.CompressFormat.JPEG,10);
               // bitmap1 = ImageCompressUtils.compressImageTO50(bitmap1);

                Bitmap bitmap2 = getBitmap(squareImage2);
                //bitmap2 = ImageCompressUtils.compressImage(bitmap2,Bitmap.CompressFormat.JPEG,10);
                //bitmap2 = ImageCompressUtils.compressImageTO50(bitmap2);

                Bitmap bitmap3 = getBitmap(squareImage3);
                //bitmap1 = ImageCompressUtils.compressImage(bitmap1,Bitmap.CompressFormat.JPEG,10);
                //bitmap3 = ImageCompressUtils.compressImageTO50(bitmap3);

                new SendSquareTask().execute(title.getText().toString(), content.getText()
                        .toString(),
                        ImageLoadUtils.saveBitmap(bitmap1, MoonConstants.TOPIC_IMAGE1),
                        ImageLoadUtils.saveBitmap(bitmap2, MoonConstants.TOPIC_IMAGE2),
                        ImageLoadUtils.saveBitmap(bitmap3, MoonConstants.TOPIC_IMAGE3));

                //startActivity(new Intent(SendSquareActivity.this, SendSquareActivity.class));
                return true;
            }

            private Bitmap getBitmap(ImageView image) {
                Drawable drawable = image.getDrawable();
                if (drawable instanceof BitmapDrawable) {
                    return ((BitmapDrawable) drawable).getBitmap();

                    //draw指定src时的情况
                } else if (drawable instanceof NinePatchDrawable) {
                    return null;
                    //                    Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable
                    //                            .getIntrinsicHeight(),
                    //                            drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
                    //                                    : Bitmap.Config.RGB_565);
                    //                    Canvas canvas = new Canvas(bitmap);
                    //                    drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
                    //                            drawable.getIntrinsicHeight());
                    //                    drawable.draw(canvas);
                    //
                    //                    bitmap = ImageCompressUtils.compressImage(bitmap, Bitmap.CompressFormat.JPEG,
                    //                            10);
                    //                    return bitmap;
                } else {
                    return null;
                }

            }
        });
        //search.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
        return super.onCreateOptionsMenu(menu);

    }
    
    
    //TODO http://w1985chun.iteye.com/blog/1685252
    //防止OOM  同时关掉了硬件加速 android:hardwareAccelerated="false"   不关仍然会出现图片过大的问题
    private Bitmap getLocalBitMap(String picturePath) throws FileNotFoundException {
        FileInputStream fis = new FileInputStream(picturePath);
        BitmapFactory.Options options=new BitmapFactory.Options();
        //options.inPreferredConfig = Bitmap.Config.RGB_565;
        options.inJustDecodeBounds = false; 
        options.inSampleSize = 5;   //width，hight设为原来的十分一 
        return BitmapFactory.decodeStream(fis,null,options); 
        
        
        
//        FileInputStream fis = new FileInputStream(picturePath);
//        BitmapFactory.Options opt = new BitmapFactory.Options();
//        opt.inPreferredConfig = Bitmap.Config.RGB_565;
//        opt.inPurgeable = true;
//        opt.inInputShareable = true;
//        return BitmapFactory.decodeStream(fis, null, opt);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
        // 如果是直接从相册获取
            case 1:
                //                Uri uri = data.getData();  
                //                Log.e("uri", uri.toString());      
                //                ContentResolver cr = this.getContentResolver();  
                try {
                    //                    Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri));  
                    //                    ImageView imageView = (ImageView) findViewById(R.id.imageView1);  
                    //                    /* 将Bitmap设定到ImageView */  
                    //                    imageView.setImageBitmap(bitmap);

                    Uri selectedImage = data.getData();
                    String[] filePathColumn = { MediaStore.Images.Media.DATA };
                    Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null,
                            null, null);
                    cursor.moveToFirst();
                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    String picturePath = cursor.getString(columnIndex);
                    cursor.close();
                    displaySquareImages(picturePath);

                } catch (Exception e) {
                    Log.e("Exception", e.getMessage(), e);
                }
                break;
            // 如果是调用相机拍照时
            case 2:
                try{
                    //File temp = new File(Environment.getExternalStorageDirectory() + "/moon_temp.jpg");
                   // FileInputStream fis = new FileInputStream(Environment.getExternalStorageDirectory() + "/moon_temp.jpg");
                    displaySquareImages(Environment.getExternalStorageDirectory() + "/moon_temp.jpg");
                }catch (Exception e) {
                    Log.e("Exception", e.getMessage(), e);
                }
               
                //Log.e("", "如果是调用相机拍照时");

                break;
            // 取得裁剪后的图片
            case 3:
                /**
                 * 非空判断大家一定要验证，如果不验证的话， 在剪裁之后如果发现不满意，要重新裁剪，丢弃
                 * 当前功能时，会报NullException，小马只 在这个地方加下，大家可以根据不同情况在合适的 地方做判断处理类似情况
                 */
                //                if (data != null) {
                //                    setPicToView(data);
                //                }
                break;
            default:
                break;

        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * @param picturePath
     * @throws FileNotFoundException
     */
    private void displaySquareImages(String picturePath) throws FileNotFoundException {
        if (selectedImageNum == 1) {
            squareImage1.setImageBitmap(getLocalBitMap(picturePath));
            squareImage2.setVisibility(View.VISIBLE);
            //利用NativeImageLoader类加载本地图片
            //                        NativeImageLoader.getInstance().loadNativeImage(picturePath, mPoint1, new NativeImageCallBack() {
            //                            @Override
            //                            public void onImageLoader(Bitmap bitmap, String path) {
            //                                squareImage1.setImageBitmap(bitmap);
            //                            }
            //                        });

            //squareImage1.setImageBitmap(BitmapFactory.decodeFile(picturePath));
            //TODO 内存问题
            //http://www.cnblogs.com/rayray/p/3180017.html
            //squareImage1.setImageBitmap(ImageCompressUtils.getimage(picturePath, Bitmap.CompressFormat.JPEG,10));
        }
        if (selectedImageNum == 2) {
            squareImage2.setImageBitmap(getLocalBitMap(picturePath));
            squareImage3.setVisibility(View.VISIBLE);

            //                        NativeImageLoader.getInstance().loadNativeImage(picturePath, mPoint2, new NativeImageCallBack() {
            //                            @Override
            //                            public void onImageLoader(Bitmap bitmap, String path) {
            //                                squareImage2.setImageBitmap(bitmap);
            //                            }
            //                        });
            //squareImage2.setImageBitmap(BitmapFactory.decodeFile(picturePath));
        }
        if (selectedImageNum == 3) {
            squareImage3.setImageBitmap(getLocalBitMap(picturePath));
            //squareImage3.setImageBitmap(BitmapFactory.decodeFile(picturePath));
            //                        NativeImageLoader.getInstance().loadNativeImage(picturePath, mPoint3, new NativeImageCallBack() {
            //                            @Override
            //                            public void onImageLoader(Bitmap bitmap, String path) {
            //                                squareImage3.setImageBitmap(bitmap);
            //                            }
            //                        });
        }
    }

    /**
     * 选择提示对话框
     */
    private void ShowPickDialog() {
        new AlertDialog.Builder(this).setTitle("选择图片")
                .setNegativeButton("相册", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        Intent intent = new Intent(Intent.ACTION_PICK, null);
                        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                                "image/*");
                        startActivityForResult(intent, 1);

                    }
                }).setPositiveButton("拍照", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        dialog.dismiss();
                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        //下面这句指定调用相机拍照后的照片存储的路径
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment
                                .getExternalStorageDirectory(), "moon_temp.jpg")));
                        startActivityForResult(intent, 2);
                    }
                }).show();
    }

    private class SendSquareTask extends AsyncTask<String, String, Boolean> {
        //public static final String TAG     = SendSquareTask.class.getSimpleName();

        String requestUrl = "/mobile_topic/create_topic.do";
       

        @Override
        protected Boolean doInBackground(String... params) {
             Date start = new Date();

            try {
                //Log.e(TAG, "SendSquare  start------------------->"+String.valueOf(new Date().getTime()));

                //请求服务器
                List<NameValuePair> pairs = convertParams(params);
                String json = HttpClientUtils.postWithImage(MoonConstants.MOON_DOMAIN + requestUrl,
                        pairs);
                JsonResult result = JacksonUtils.fromJSON(json, JsonResult.class);
                if (result.isSuccess()) {
                    Date end = new Date();

                    Log.e(TAG, "SendSquare  ------------------->"+(end.getTime() - start.getTime()));

                    return true;
                } else {
                    //                    if (StringUtils.isNotBlank(result.getMessage())) {
                    //                        publishProgress(result.getMessage());
                    //                    }
                    return false;
                }
            } catch (Exception e) {
                // 提示用户网络异常
                String message = getString(R.string.network_error);
                Log.e(TAG, message, e);
                publishProgress(message);
                return false;
            }
        }

        @Override
        protected void onProgressUpdate(String... values) {
            Toast.makeText(getApplicationContext(), values[0], Toast.LENGTH_SHORT).show();
        }

        //要更新UI,必须重写此方法,不能在doInBackground直接操作UI
        @Override
        protected void onPostExecute(Boolean result) {
            if (result) {
                //返回列表
                startActivity(new Intent(TopicSendActivity.this, TopicListActivity.class));
            } else {
                Toast.makeText(getApplicationContext(), "发送失败", Toast.LENGTH_SHORT).show();
            }
        }

        /**
         * 组装request参数
         * 
         * @param params
         * @return
         */
        private List<NameValuePair> convertParams(String... params) {
            List<NameValuePair> pairs = new ArrayList<NameValuePair>();
            pairs.add(new BasicNameValuePair(MoonConstants.TOPIC_TITLE, params[0]));
            pairs.add(new BasicNameValuePair(MoonConstants.TOPIC_CONTENT, params[1]));
            if (params[2] != null) {
                pairs.add(new BasicNameValuePair(MoonConstants.TOPIC_IMAGE1, params[2]));
            }
            if (params[3] != null) {
                pairs.add(new BasicNameValuePair(MoonConstants.TOPIC_IMAGE2, params[3]));
            }
            if (params[4] != null) {
                pairs.add(new BasicNameValuePair(MoonConstants.TOPIC_IMAGE3, params[4]));
            }

            pairs.add(new BasicNameValuePair(MoonConstants.TOPIC_USER_ID, String.valueOf(getUser()
                    .getId())));
            pairs.add(new BasicNameValuePair(MoonConstants.TOPIC_CATEGORY_ID, topicId));

            return pairs;
        }

    }

    /**
     * @return
     */
    private String validate() {

        if (StringUtils.isBlank(title.getText().toString())) {
            return "主题不能为空";
        }

        if (title.getText().toString().length() > 30) {
            return "主题太长,不能超过30个字符";
        }
        if (StringUtils.isBlank(content.getText().toString())) {
            return "内容不能为空";
        }
        return null;
    }
    
    
}
